<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>参数列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片区域 -->
    <el-card>
      <!-- 提示区域 -->
      <el-alert
        title="注意：只允许为第三级分类设置相关参数"
        type="warning"
        show-icon
        :closable="false"
      >
      </el-alert>

      <!-- 商品分类选择区域 -->
      <el-row>
        <el-col>
          <span>选择商品分类: </span>

          <!-- 级联选择框 -->
          <el-cascader
            v-model="selectedCateKeys"
            :options="cateList"
            :props="cateProps"
            @change="handleChange"
          >
          </el-cascader>
        </el-col>
      </el-row>

      <!-- tab页签区域 -->
      <el-tabs v-model="activeName" @tab-click="handleClick">
        <!-- 动态参数的面板 -->
        <el-tab-pane label="动态参数" name="many">
          <el-button type="primary" size="mini" :disabled="isDisabled" @click="addDialogVisible = true">添加参数</el-button>

          <!-- 显示动态参数的表格 -->
          <el-table :data="manyTableDate" border stripe>
            <!-- 展开 -->
            <el-table-column type="expand">
              <template slot-scope="scope">
                <!-- 标签区域 -->
                <el-tag closable v-for="(item, index) in scope.row.attr_vals" :key="index" @close="tagClosed(item, scope.row)">{{ item }}</el-tag>
                <!-- 输入框区域 -->
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)">
                </el-input>
                <!-- 按钮区域 -->
                <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
              </template>
            </el-table-column>

            <!-- 序号列 -->
            <el-table-column type="index"></el-table-column>

            <!-- 参数列 -->
            <el-table-column label="参数" prop="attr_name"></el-table-column>

            <!-- 操作列 -->
            <el-table-column label="操作">
              <!-- 两个操作按钮 -->
              <template slot-scope="scope">
                <el-button type="primary" size="mini" el-icon-edit @click="showEditDialog(scope.row.attr_id)">编辑</el-button>
                <el-button type="danger" size="mini" el-icon-delete @click="deleteParams(scope.row.attr_id)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>

        <!-- 静态属性的面板 -->
        <el-tab-pane label="静态属性" name="only">
          <el-button type="primary" size="mini" :disabled="isDisabled"
            @click="addDialogVisible = true">添加属性</el-button>

          <!-- 显示静态属性的表格 -->
          <el-table :data="onlyTableDate" border stripe>
            <!-- 展开 -->
            <el-table-column type="expand">
              <template slot-scope="scope">
                <!-- 标签区域 -->
                <el-tag closable v-for="(item, index) in scope.row.attr_vals" :key="index" @close="tagClosed(item, scope.row)">{{ item }}</el-tag>
                <!-- 输入框区域 -->
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)">
                </el-input>
                <!-- 按钮区域 -->
                <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
              </template>
            </el-table-column>

            <!-- 序号列 -->
            <el-table-column type="index"></el-table-column>

            <!-- 参数列 -->
            <el-table-column label="参数" prop="attr_name"></el-table-column>

            <!-- 操作列 -->
            <el-table-column label="操作">
              <!-- 两个操作按钮 -->
              <template slot-scope="scope">
                <el-button type="primary" size="mini" el-icon-edit @click="showEditDialog(scope.row.attr_id)">编辑</el-button>
                <el-button type="danger" size="mini" el-icon-delete @click="deleteParams(scope.row.attr_id)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>

    <!-- 添加对话框 -->
    <el-dialog :title="'添加' + addTitle" :visible.sync="addDialogVisible" width="50%" @close="addDialogClosed">
      <!-- 添加对话框表单区域 -->
      <el-form :model="addForm" :rules="addFormRuls" ref="addFormRef" label-width="100px">
        <el-form-item :label="addTitle" prop="attr_name">
          <el-input v-model="addForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addParams">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 编辑对话框 -->
    <el-dialog :title="'修改' + addTitle" :visible.sync="editDialogVisible" width="50%" @close="editDialogClosed">
      <!-- 添加对话框表单区域 -->
      <el-form :model="editForm" :rules="editFormRuls" ref="editFormRef" label-width="100px">
        <el-form-item :label="addTitle" prop="attr_name">
          <el-input v-model="editForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span class="dialog-footer"  slot="footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editParams">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      // 商品分类列表
      cateList: [],

      // 级联选择框的配置对象
      cateProps: {
        value: 'cat_id',
        label: 'cat_name',
        children: 'children'
      },

      // 存放选中分类的id值
      selectedCateKeys: [],

      // tabs默认选择的页签
      activeName: 'many',

      // 存放动态参数
      manyTableDate: [],

      // 存放静态参数
      onlyTableDate: [],

      // 添加对话框的显示与隐藏
      addDialogVisible: false,

      // 编辑对话框的显示与隐藏
      editDialogVisible: false,

      // 添加框表单对象
      addForm: {
        attr_name: ''
      },

      // 编辑框表单对象
      editForm: {
      },

      // 添加框表单验证规则
      addFormRuls: {
        attr_name: [{ required: true, message: '请输入参数', trigger: 'blur' }]
      },

      // 编辑框表单验证规则
      editFormRuls: {
        attr_name: [{ required: true, message: '请输入参数', trigger: 'blur' }]
      }
    }
  },

  // 创建
  created() {
    this.getCateList()
  },

  // 方法
  methods: {
    // 获取所有商品的分类列表
    async getCateList() {
      const { data: res } = await this.$http.get('categories')
      if (res.meta.status !== 200) return this.$message.error('获取商品分类列表失败')
      this.cateList = res.data
    },

    // 级联选择框选中变化会触发
    handleChange() {
      this.getParmasDate()
    },

    // tab页签点击处理的函数
    handleClick() {
      this.getParmasDate()
    },

    // 获取参数
    async getParmasDate() {
      if (this.selectedCateKeys.length !== 3) {
        this.selectedCateKeys = []
      }
      // 根据分类获取参数
      const { data: res } = await this.$http.get(
        `categories/${this.cateId}/attributes`,
        {
          params: { sel: this.activeName }
        }
      )
      if (res.meta.status !== 200) return this.$message.error('获取数据失败')

      // 将数据中的attr_vals变为数组
      res.data.forEach(item => {
        item.attr_vals = item.attr_vals ? item.attr_vals.split(' ') : []
        item.inputVisible = false
        item.inputValue = ''
      })
      // 判断是静态参数还是动态参数
      if (this.activeName === 'many') {
        this.manyTableDate = res.data
      } else {
        this.onlyTableDate = res.data
      }
    },

    // 监听添加框关闭时触发
    addDialogClosed() {
      this.$refs.addFormRef.resetFields()
    },

    // 监听编辑对话框关闭时触发
    editDialogClosed() {
      this.$refs.editFormRef.resetFields()
    },

    // 添加动态参数或静态属性
    addParams() {
      // post数据之前先进行表单验证
      this.$refs.addFormRef.validate(async valid => {
        if (!valid) return
        const { data: res } = await this.$http.post(`categories/${this.cateId}/attributes`, {
          attr_name: this.addForm.attr_name,
          attr_sel: this.activeName
        })
        if (res.meta.status !== 201) return this.$message.error('添加失败')
        this.$message.success('添加成功')
        this.addDialogVisible = false
        this.getParmasDate()
      })
    },

    // 编辑动态参数和静态属性
    editParams() {
      this.$refs.editFormRef.validate(async valid => {
        if (!valid) return
        const { data: res } = await this.$http.put(`categories/${this.cateId}/attributes/${this.editForm.attr_id}`, {
          attr_name: this.editForm.attr_name,
          attr_sel: this.activeName
        })
        if (res.meta.status !== 200) return this.$message.error('修改参数失败')
        this.$message.success('修改参数成功')
        this.editDialogVisible = false
        this.getParmasDate()
      })
    },

    // 显示动态参数和静态属性编辑框
    async showEditDialog(id) {
      const { data: res } = await this.$http.get(`categories/${this.cateId}/attributes/${id}`, { params: { attr_sel: this.activeName } })
      if (res.meta.status !== 200) return this.$message.error('获取失败')
      this.editForm = res.data
      this.editDialogVisible = true
    },

    // 删除动态参数和静态属性
    async deleteParams(id) {
      const confirmResult = await this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      if (confirmResult === 'cancel') return this.$message.warning('取消了删除')
      const { data: res } = await this.$http.delete(`categories/${this.cateId}/attributes/${id}`)
      if (res.meta.status !== 200) return this.$message.error('删除失败')
      this.$message.success('删除成功')
      this.getParmasDate()
    },

    // 选择框失去焦点时触发
    async handleInputConfirm(row) {
      if (row.inputValue.trim().length === 0) {
        row.inputValue = ''
        row.inputVisible = false
        return
      }
      row.attr_vals.push(row.inputValue)
      row.inputValue = ''
      row.inputVisible = false
      const { data: res } = await this.$http.put(`categories/${this.cateId}/attributes/${row.attr_id}`, {
        attr_name: row.attr_name,
        attr_sel: row.attr_sel,
        attr_vals: row.attr_vals.join(' ')
      })
      if (res.meta.status !== 200) return this.$message.error('更新数据失败')
      this.$message.success('更新数据成功')
    },

    // 按钮点击时触发
    showInput(row) {
      row.inputVisible = true
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },

    // Tag标签关闭时触发
    async tagClosed(item, row) {
      row.attr_vals.splice(row.attr_vals.indexOf(item), 1)
      const { data: res } = await this.$http.put(`categories/${this.cateId}/attributes/${row.attr_id}`, {
        attr_name: row.attr_name,
        attr_sel: row.attr_sel,
        attr_vals: row.attr_vals.join(' ')
      })
      if (res.meta.status !== 200) return this.$message.error('更新数据失败')
      this.$message.success('更新数据成功')
    }
  },

  // 计算属性
  computed: {
    // 如果按钮需要被禁用,则返回true,否则返回false
    isDisabled() {
      if (this.selectedCateKeys.length !== 3) {
        return true
      }
      return false
    },

    // 获取点击三级分类的id
    cateId() {
      if (this.selectedCateKeys.length === 3) {
        return this.selectedCateKeys[2]
      }
      return null
    },

    // 添加对话框的标题
    addTitle() {
      if (this.activeName === 'many') {
        return '动态参数'
      } else {
        return '静态属性'
      }
    }
  }
}
</script>

<style lang="less" scoped>
.el-row {
  margin: 30px 0;
}

.el-tag {
  margin-right: 10px;
}

.input-new-tag {
  width: 100px;
}
</style>
